package com.gln.bloger.service.impl;

import java.util.List;

import com.gln.bloger.dao.CategoryDao;
import com.gln.bloger.exception.AlreadyExistException;
import com.gln.bloger.exception.BlogerException;
import com.gln.bloger.log.Logging;
import com.gln.bloger.pojos.Category;
import com.gln.bloger.pojos.Website;
import com.gln.bloger.service.CategoryService;
import com.gln.bloger.util.PagingSupport;
import com.gln.bloger.util.StringUtil;

public class CategoryServiceImpl implements CategoryService {
    
	private CategoryDao categoryDao;
    
	private List<Category> cachedCategories;
    
	public CategoryDao getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	public PagingSupport<Category> getAllCategories(Website website)
	throws BlogerException {
		List<Category> data = getCategoryDao().getAllCategories(website);
		PagingSupport<Category> categories = new PagingSupport<Category>();
		categories.setData(data);
		return categories; 
    }

	public PagingSupport<Category> getCategories(Website website)
	throws BlogerException {
		List<Category> data = getCategoryDao().getCategories(website);
		PagingSupport<Category> categories = new PagingSupport<Category>();
		categories.setData(data);
		return categories;
	}

	public Category getCategory(String cateId) throws BlogerException {
		Category cate =  getCategoryDao().get(cateId);
		return cate;
	}
	public Category getCategoryByName(Website website, String cateName) throws BlogerException {
	    Category category = getCategoryDao().getByName(website, cateName);
	    return category;
	}

	public void removeCategory(String cateId) throws BlogerException {
		Category cate = getCategoryDao().get(cateId);
		getCategoryDao().remove(cate);
	}

	public void saveOrUpdateCategory(Category category) throws BlogerException {
		/**
		 * insert category , check if exsit
		 */
		if(StringUtil.isBlank(category.getId())){
			Category cateInDb = getCategoryByName(category.getWebsite(), category.getName());
			
			if(null != cateInDb){
				throw new AlreadyExistException();
			}
		}
		getCategoryDao().saveOrUpdate(category);
	}

	public void clearCachedCategories() {
		if(this.cachedCategories != null){
		    this.cachedCategories.clear();
		}
	}

	public List<Category> getCategoryList(Website website)
			throws BlogerException {
		if(this.cachedCategories != null && this.cachedCategories.size() != 0){
			Logging.debug("load category list from app cache");
		}else{
			this.cachedCategories = this.getCategoryDao().getCategories(website);
		}
		return this.cachedCategories;
	}
}
